package com.share.schedule.simple.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.share.common.utils.HttpUtil;
import com.share.common.utils.ObjUtil;
import com.share.schedule.simple.dao.Sf202102TaskMapper;
import com.share.schedule.simple.dao.Sf202102VehicleMapper;
import com.share.schedule.simple.dao.Sf202102VehicleTaskMapper;
import com.share.schedule.simple.model.db.Sf202102Vehicle;
import com.share.schedule.simple.model.db.Sf202102VehicleTask;
import com.share.schedule.simple.model.dto.SfPeakSyncPlanTaskParam;
import com.share.schedule.simple.model.dto.SfPeakSyncVehicleDetailParam;
import com.share.schedule.simple.service.SfPeakService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 01401061 - 孙艳强
 * @date 2021/1/31 18:58
 */
@Slf4j
@Service
public class SfPeakServiceImpl implements SfPeakService {
    @Resource
    private Sf202102VehicleMapper sf202102VehicleMapper;

    @Resource
    private Sf202102VehicleTaskMapper sf202102VehicleTaskMapper;

    @Resource
    private Sf202102TaskMapper sf202102TaskMapper;

    /**
     * 车辆情况同步
     *
     * @param param
     * @return
     */
    @Override
    public int syncVehicleRunDetail(SfPeakSyncVehicleDetailParam param) {
        JSONArray jsonArray = httpSyncVehicleRunDetail(param);
        if (jsonArray == null || jsonArray.size() == 0) {
            log.info("cookie可能过期了！！！");
            return -1;
        } else {
            log.info("同步查询到记录" + jsonArray.size() + "数");
        }

        int add = 0;
        int update = 0;
        Date curDate = new Date();
        for (Object obj : jsonArray) {
            JSONObject jsonObj = (JSONObject) obj;

            //基本信息
            Sf202102Vehicle record = jsonObj.toJavaObject(Sf202102Vehicle.class);
            if (record != null && record.getVehicleCode() != null) {
                Sf202102Vehicle sf202102Vehicle = sf202102VehicleMapper.selectByPrimaryKey(record.getVehicleCode());
                record.setUpdateTime(curDate);
                if (sf202102Vehicle == null) {
                    sf202102VehicleMapper.insert(record);
                    add++;
                } else {
                    sf202102VehicleMapper.updateByPrimaryKey(record);
                    update++;
                }
            }

            //历史任务
            Sf202102VehicleTask taskInstace = null;
            taskInstace = jsonObj.getObject("beforeTask", Sf202102VehicleTask.class);
            if (taskInstace != null && taskInstace.getTaskId() != null) {
                Sf202102VehicleTask tmpRecord = sf202102VehicleTaskMapper.selectByPrimaryKey(taskInstace.getTaskId());
                taskInstace.setUpdateTime(curDate);
                taskInstace.setVehicleCode(record.getVehicleCode());
                if (tmpRecord == null) {
                    sf202102VehicleTaskMapper.insert(taskInstace);
                    add++;
                } else {
                    sf202102VehicleTaskMapper.updateByPrimaryKey(taskInstace);
                    update++;
                }
            }

            //当前任务
            taskInstace = jsonObj.getObject("currentTask", Sf202102VehicleTask.class);
            if (taskInstace != null && taskInstace.getTaskId() != null) {
                Sf202102VehicleTask tmpRecord = sf202102VehicleTaskMapper.selectByPrimaryKey(taskInstace.getTaskId());
                taskInstace.setUpdateTime(curDate);
                taskInstace.setVehicleCode(record.getVehicleCode());
                if (tmpRecord == null) {
                    sf202102VehicleTaskMapper.insert(taskInstace);
                    add++;
                } else {
                    sf202102VehicleTaskMapper.updateByPrimaryKey(taskInstace);
                    update++;
                }
            }

            //下一个任务
            taskInstace = jsonObj.getObject("nextTask", Sf202102VehicleTask.class);
            if (taskInstace != null && taskInstace.getTaskId() != null) {
                Sf202102VehicleTask tmpRecord = sf202102VehicleTaskMapper.selectByPrimaryKey(taskInstace.getTaskId());
                taskInstace.setUpdateTime(curDate);
                taskInstace.setVehicleCode(record.getVehicleCode());
                if (tmpRecord == null) {
                    sf202102VehicleTaskMapper.insert(taskInstace);
                    add++;
                } else {
                    sf202102VehicleTaskMapper.updateByPrimaryKey(taskInstace);
                    update++;
                }
            }

        }

        return update + add;
    }

    private JSONArray httpSyncVehicleRunDetail(SfPeakSyncVehicleDetailParam param) {
        String reqUrl = "https://tbp.sf-express.com/dispatchCal/vehicleBizQuery/vehicleOverviewQuery";

        String cookie = "a_authorization_login=80004950; a_authorization=57fe118c-3f69-4bc1-b428-4198fd825275/904683fd-619a-4ac5-8d02-0448f3fd53fd/94911AB9D3A47725567FE0FB9BDC5C1C; _TOKEN_KEY_=eyJhbGciOiJIUzI1NiJ9.eyJyb2xlSWQiOiIxMDAxODQiLCJpc3MiOiI4MDAwNDk1MCIsImV4cCI6MTYxMjE4MjIxMn0.86kwFrEAOxHpysmDa1JKX8Mty1PboigBzL9yzERaIx0; JSESSIONID=13yqdkug9dq4syquukvjetmsx";

        Map<String, String> headMap = new HashMap<>();
        headMap.put("Cookie", cookie);
        headMap.put("Accept", "application/json, text/plain, */*");
        headMap.put("Accept-Encoding", "gzip, deflate");
        headMap.put("Accept-Language", "zh-CN,zh;q=0.9");
        headMap.put("Cache-Control", "no-cache");
        headMap.put("Connection", "keep-alive");
        headMap.put("Content-Type", "application/json;charset=UTF-8");
        headMap.put("gw-bdus-rid", "7130");
        headMap.put("Host", "tbp.sf-express.com");
        headMap.put("lang", "zh-CN");
        headMap.put("Origin", "https://tbp.sf-express.com");
        headMap.put("Referer", "https://tbp.sf-express.com/module/index.html");
        headMap.put("Sec-Fetch-Dest", "empty");
        headMap.put("Sec-Fetch-Mode", "cors");
        headMap.put("Sec-Fetch-Site", "same-origin");
        headMap.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
        headMap.put("X-Requested-With", "XMLHttpRequest");

        headMap.put("SfopenReferer", "https://tbp.sf-express.com/module/index.html");
        try {
            String reStr = HttpUtil.post(reqUrl, JSON.toJSONString(param), headMap);
            JSONObject re = JSON.parseObject(reStr);
            JSONObject result = re.getJSONObject("result");
            JSONArray datas = result.getJSONArray("datas");
            return datas;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private JSONArray driver(String driverPhone) {
        String reqUrl = "https://tbp.sf-express.com/resource/driverMgrController/queryPage";

        String cookie = "JSESSIONID=1hhnjmdurlo7b8ild2kqpr4qp; SESSION=19880d18-eb80-4316-86f8-c2c1c7b99f4c; JSESSIONID=e78rksrw52u71m2qg6a79z2jf; _TOKEN_KEY_=eyJhbGciOiJIUzI1NiJ9.eyJyb2xlSWQiOiIxMDAxODQiLCJpc3MiOiIwNDQ2ODYiLCJleHAiOjE2MTI1MjM0MjZ9.yXGajvlSaboWcA0CpHtCer1DTd_njT6pCkmy1SFDsVw";

        Map<String, String> headMap = new HashMap<>();
        headMap.put("Cookie", cookie);
        headMap.put("Accept", "application/json, text/plain, */*");
        headMap.put("Accept-Encoding", "gzip, deflate");
        headMap.put("Accept-Language", "zh-CN,zh;q=0.9");
        headMap.put("Cache-Control", "no-cache");
        headMap.put("Connection", "keep-alive");
        headMap.put("Content-Type", "application/json;charset=UTF-8");
        headMap.put("gw-bdus-rid", "7130");
        headMap.put("Host", "tbp.sf-express.com");
        headMap.put("lang", "zh-CN");
        headMap.put("Origin", "https://tbp.sf-express.com");
        headMap.put("Referer", "https://tbp.sf-express.com/module/index.html");
        headMap.put("Sec-Fetch-Dest", "empty");
        headMap.put("Sec-Fetch-Mode", "cors");
        headMap.put("Sec-Fetch-Site", "same-origin");
        headMap.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
        headMap.put("X-Requested-With", "XMLHttpRequest");

        headMap.put("SfopenReferer", "https://tbp.sf-express.com/module/index.html");


        JSONObject obj = new JSONObject();
        obj.put("mobilephone", driverPhone);
        obj.put("page", 0);
        obj.put("pageSize", 10);
        try {
            String reStr = HttpUtil.post(reqUrl, JSON.toJSONString(obj), headMap);
            JSONObject re = JSON.parseObject(reStr);
            JSONObject result = re.getJSONObject("result");
            JSONArray datas = result.getJSONArray("datas");
            return datas;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 任务同步
     *
     * @param planTask
     * @return
     */
    @Override
    public int syncPlanTask(SfPeakSyncPlanTaskParam planTask) {
        String reqUrl = "https://tbp.sf-express.com/platformManagement/queryTaskMonitoringPage.arz";
        Map<String, String> headMap = new HashMap<>();
        headMap.put("Cookie", "SESSION=2cca548c-673e-4109-ab1c-f6cf6037c2bb; JSESSIONID=d77nvtwq1g5e1r5e9l58429cz; _TOKEN_KEY_=eyJhbGciOiJIUzI1NiJ9.eyJyb2xlSWQiOiIxMDAxODQiLCJpc3MiOiIwNDQ2ODYiLCJleHAiOjE2MTIxNjkyMzV9.bqbGEmseX5Pdqcog369VULfvnuwNfKXzQ294DnBHH2Y; JSESSIONID=1fufqnlsw9idx1czsemb2uniu1");

        headMap.put("Accept", "application/json, text/plain, */*");
        headMap.put("Accept-Encoding", "gzip, deflate");
        headMap.put("Accept-Language", "zh-CN,zh;q=0.9");
        headMap.put("Cache-Control", "no-cache");
        headMap.put("Connection", "keep-alive");
//        headerParams.put("Content-Length", "124");
        headMap.put("Content-Type", "application/json;charset=UTF-8");
        headMap.put("gw-bdus-rid", "7130");
        headMap.put("Host", "tbp.sf-express.com");
        headMap.put("lang", "zh-CN");
        headMap.put("Origin", "https://tbp.sf-express.com");
        headMap.put("Referer", "https://tbp.sf-express.com/platformManagement/taskMonitoringPlatform.arz");
        headMap.put("Sec-Fetch-Dest", "empty");
        headMap.put("Sec-Fetch-Mode", "cors");
        headMap.put("Sec-Fetch-Site", "same-origin");
        headMap.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
        headMap.put("X-Requested-With", "XMLHttpRequest");

        try {
            //String reStr = HttpRequestUtils.postSSLWithJsonParam(reqUrl,planTask,headMap);
            String str = ObjUtil.toKv(planTask);
            String reStr = HttpUtil.post(reqUrl, str, headMap);
            System.out.println(reStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static void main(String[] args) {
        SfPeakServiceImpl peak = new SfPeakServiceImpl();


        //SfPeakSyncPlanTaskParam param  = new SfPeakSyncPlanTaskParam();
        //param.setPlanSendTime("2021-02-01 00:00");
        //param.setPlanArriveTime("2021-02-02 00:00");
        //peak.syncPlanTask(param);

        //SfPeakSyncVehicleDetailParam param = new SfPeakSyncVehicleDetailParam();
        //param.setMotorcadeName("2021年春节高峰杭州-上海车");
        //peak.syncVehicleRunDetail(param);

        int cout = 0;
        StringBuffer sb = new StringBuffer();
        String str = "13833111283,13833111283,13833111283,13833111283,18317882373,15256827953,15256827953,15256827953,18818197090,18818197090,18818197090,18818197090,18754564926,18827790519,18827790519,15961995420,19136095350,18662355180,13758345621,13856800168,15055747020,15055747020,15055747020,15055747020,15896829936,15896829936,15896829936,15896829936,15896829936,15896829936,13869778187,18606830185,18606830185,18606830185,18606830185,18606830185,13869778187,18257198576,15026287523,18726671199,18603069126,18916729906,18609681008,18609681008,18609681008,13173602659,13376829801,15967694073,15967694073,13856800168,13856800168,13912378438,13912378438,13912378438,15703824459,15703824459,15703824459,15703824459,15703824459,17551004059,17551004059,17551004059,15256827953,15256827953,15256827953,,,,15256827953,18754564926,18754564926,18754564926,18754564926,18754564926,18912771172,15554549319,18257198576,18257198576,18257198576,17625967853,17625967853,17625967853,15399554918,15399554918,15399554918,15399554918,15399554918,18827790519,18827790519,18827790519,18827790519,18827790519,18121658286,15961995420,15152331200,15152331200,15312229726,17821039390,17821039390,17821039390,17821039390,14753874666,14753874666,14753874666,14753874666,14753874666,14753874666,15872308848,15872308848,15295751068,18662355180,18662355180,18662355180,18603069126,15026287523,15026287523,15026287523,15026287523,18709894380,18709894380,18709894381,13788946991,15221039347,15221039347,15221039347,13863210326,13863210326,13482167091,13482167091,13482167091,13837828671";
        String[] split = str.split(",");
        for (String s : split) {
            JSONArray arr = peak.driver(s);
            if (arr != null && arr.size() == 1) {
                JSONObject jsn = (JSONObject) arr.get(0);
                String item = "phone=" + s + ",userId=" + jsn.getString("userName");
                sb.append(item + System.lineSeparator());
                System.err.println(item);
            }
            cout++;
        }

        System.err.println(sb.toString());
        System.err.println(cout);
    }
}